package xiegd.study.proxy.jdk;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: xieguangda
 * @Description:
 * @Date: 2023/9/21 14:45
 */
@Component
public class StudentBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("我的beanName:::::"+ beanName);

        if("studentDoImpl".equals(beanName)){
            //使用jdk动态代理；
            Class<?> aClass = bean.getClass();
            Class<?>[] interfaces = aClass.getInterfaces();
            ClassLoader classLoader = aClass.getClassLoader();
            InvocationHandler invocationHandler = new InvocationHandler(){
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("再学生钱前面");
                    System.out.println("proxy:" + proxy.getClass());
                    Object invoke = null;
                    try{
                        invoke = method.invoke(bean, args);
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println("再学生钱后面");
                    return invoke;
                }
            };
            Object o = Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);

            System.out.println("proxy2:" + o.getClass());
//            Object o =  Proxy.newProxyInstance(classLoader, interfaces, (proxy, method, args) ->
//            {
//                System.out.println("再学生钱前面");
//                Object invoke = null;
//                try{
//                    System.out.println("我被输出了" + proxy + ",,,,," + bean);
//                    invoke = method.invoke(bean, args);
//                } catch (Exception e){
//                    e.printStackTrace();
//                }
//                    System.out.println("再学生钱后面");
//                return invoke;
//            });


            return o;
        }
        return bean;
    }
}
